#coding=utf8
from google.appengine.ext import db
import datetime,logging
from counter import get_count, change_count

def str2date(s):
    '''2002-04-09 --> date type'''
    return datetime.date( *map(int, s.split('-')) )
    
class Stock(db.Model):
    code = db.StringProperty(required=True)
    
    name = db.StringProperty()
    market = db.StringProperty()
    
    ipo = db.DateProperty()
    iprice = db.FloatProperty()
    
    created_at = db.DateProperty(auto_now_add=True)
    updated_at = db.DateTimeProperty()
    
    def delete(self):        
    
        super(Stock, self).delete()
        logging.info('%s:delelted'%self.code)
        change_count(-1)
        logging.info('-1')
                
    def update_tss(self, tss):
        '''tss: 像 [['2002-07-10', '653655400'],...,['2002-04-09', '600000000']]的数据'''
        for ts in tss:
            t = self.tss.filter('value =', int(ts[1])).fetch(1)
            if t:continue
            else:
                t = TradableShare()
                t.s = self
                t.value = int(ts[1])
                t.since = str2date(ts[0])
                t.put()
        
        now = datetime.datetime.now()
        self.updated_at = now
        self.put()
        
    def get_current_ts(self): 
        return self.tss.order('-since').fetch(1)[0].value
    ts = property(get_current_ts)
     
    def to_dict(self):
        d = {}
        attrs = ['code', 'name', 'market', 'ipo', 'iprice', 'created_at', 'updated_at']
        for attr in attrs:
            d[attr] = getattr(self, attr, '')
        #d['name'] = d['name'].encode('u8')
        return d
        
    def tss_to_dict(self):
        
        tss = []
        for ts in self.tss.order('-since'):
            tss.append(ts.to_list())
       
        return { self.code:tss }
            
class TradableShare(db.Model):
    s = db.ReferenceProperty(Stock, collection_name='tss')

    value = db.IntegerProperty()
    since = db.DateProperty()

    created_at = db.DateProperty(auto_now_add=True)
    
    def to_list(self):
        return [self.since, self.value, self.created_at]    
        
def create_stock(stock_data):
    '''stock_data: stockcrawler.get_stock的返回值'''
    
    code = stock_data['code']
    s = Stock(code=code, key_name='stock_%s'%code)
    
    s.name = unicode( stock_data['name'], 'u8')
    s.market = stock_data['market']
    s.ipo = str2date( stock_data['ipo'] )
    s.iprice = float( stock_data['iprice'] )
    try:
        s.put()
        change_count(1)
        #logging.info('%s created.'%code)
    except Exception,e:
        logging.info(e)
    return s

def stock_count():
    return get_count()

class Code(db.Model):
    code = db.StringProperty(required=True)
    
def put_codes(codelist):
    n = 200
    while True:
        if not codelist:return
        a,codelist = codelist[:n], codelist[n:]
        cs = [Code(code=c) for c in a]
        db.put(cs)

def get_stock(code):
    
    key_name='stock_%s'%code
    s = Stock.get_by_key_name(key_name)
    
    return s
